package com.shuai.chatroom.service;

import com.shuai.chatroom.common.AppConstant;
import com.shuai.chatroom.entity.MessageInfo;
import com.shuai.chatroom.entity.vo.MessageInfoVO;
import com.shuai.chatroom.exception.ServiceException;
import com.shuai.chatroom.mapper.MessageMapper;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

@Service
public class MessageService {
    @Resource
    private MessageMapper messageMapper;

    public MessageInfo getLastMessageInfo(Integer sessionId) {
        return messageMapper.getLastMessageInfo(sessionId);
    }

    //返回会话中最近的100条信息
    public List<MessageInfoVO> getHistoryMessageList(Integer sessionId) {
        return messageMapper.getHistoryMessageList(sessionId);
    }

    public int addMessage(MessageInfo messageInfo) {
        return messageMapper.addMessage(messageInfo);
    }

    //获取指定会话中的未读消息条数
    public int getNoReadMessNum(Integer sessionId, Integer uId) {
        return messageMapper.getNoReadMessNum(sessionId, uId);
    }


    //更新指定会话中消息的状态为已读
    public int updateMessState(Integer sessionId) {
        return messageMapper.updateMessState(sessionId);
    }


    @Value("${up_file_path}")
    private String rootPath;    //文件在本地磁盘的保存路径


    @Value("${up_file_relative_path}")
    private String visitPathPre;

    /**
     * 将前端上传的文件保存到本地磁盘，将其作为一条消息记录插入到message表中
     */
    @Transactional
    public String uploadFile(MultipartFile file, MessageInfo messageInfo) throws ServiceException {
        String originalFilename = file.getOriginalFilename();
        String fileSavePath;
        String fileName;
        if (originalFilename != null && originalFilename.contains(".")) {
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));  //读取文件后缀
            fileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            fileSavePath = rootPath + fileName;
            try {
                file.transferTo(new File(fileSavePath));
            } catch (IOException e) {
                throw new ServiceException("文件保存失败！");
            }
        } else {
            throw new ServiceException("文件格式错误！");
        }
        messageInfo.setMessType(AppConstant.MESSAGE_TYPE_FILE); //设置消息类型为文件类型
        String visitPath = visitPathPre + fileName;
        messageInfo.setMessContent(visitPath);
        messageInfo.setOriginalFileName(file.getOriginalFilename());
        messageMapper.addMessage(messageInfo);
        return visitPath;
    }
}
